package io;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

import constants.Constants;
import model.i.IState;

/**
 * Responsible for serializing game states and storing them
 * in the file system.
 */
public class Save {

    private String file;
    private IState s;

    /**
     * Create a Save object that is ready to
     * store the given state at the given file path.
     * Note that writeToFile has to be called to do the IO.
     * @param s the state to save
     * @param file the desired file path
     */
    public Save(IState s, String file){
        this.s = s;
        this.file = file;
    } //Constructor

    /**
     * If the file path does not end properly, append the
     * correct file extension from Constants.IO
     * @param s the file path from the constructor
     * @return the same path, with a valid filename
     */
    private String addExtensionIfMissing(String s){
        if(file.endsWith(Constants.IO.file_ext_save)){
            return s;
        }
        return s + Constants.IO.file_ext_save;
    }

    /**
     * Creates a file with the data specified when constructing this Save object
     */
    public void writeToFile(){
        file = addExtensionIfMissing(file);

        ObjectOutputStream outputStream = null;
        try{
            outputStream = new ObjectOutputStream(new FileOutputStream(file,false));
            outputStream.writeObject(s);

        } catch (FileNotFoundException ex){
            ex.printStackTrace();
        } catch (IOException ex){
            ex.printStackTrace();
        } finally {
            try{
                if(outputStream != null){
                    outputStream.flush();
                    outputStream.close();
                }
            } catch (IOException ex){
                ex.printStackTrace();
            }
        }
    }
}
